package ynu.edu.common.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "enabled", havingValue = "true", matchIfMissing = false)
public class RabbitMQConfigTemplate {

    // 连接工厂（参数由各个微服务的YAML提供）
    @Bean
    public ConnectionFactory connectionFactory(
            @Value("${spring.rabbitmq.host:192.168.119.128}") String host,
            @Value("${spring.rabbitmq.port:5672}") int port,
            @Value("${spring.rabbitmq.username:root}") String username,
            @Value("${spring.rabbitmq.password:123123}") String password
    ) {
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setHost(host);
        factory.setPort(port);
        factory.setUsername(username);
        factory.setPassword(password);
        return factory;
    }

    // 生产者使用的模板
    @Bean
    @Primary
    public RabbitTemplate customRabbitTemplate(ConnectionFactory factory) {
        return new RabbitTemplate(factory);
    }

    // 消费者监听的容器工厂（手动ACK）
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            ConnectionFactory factory
    ) {
        SimpleRabbitListenerContainerFactory listener = new SimpleRabbitListenerContainerFactory();
        listener.setConnectionFactory(factory);
        listener.setAcknowledgeMode(AcknowledgeMode.MANUAL); // 手动ACK
        return listener;
    }

}